# 1.
# 读取cookie
# 2.
# 读取redis
# 3.
# 初始化了3个容器
# 一个列表用于存放选中的id
# 一个列表用于存放未选中的id
# 一个字典用于保存cookie中的转换为hash的数据
# 4.
# 对cookie数据进行遍历
# 进行判断 如果数据存在 则一cookie为主 如果数据不存在 新加
# 5.
# 更新redis
# 6.
# cookie删除
import base64
import pickle

from django_redis import get_redis_connection


def merge_cookie_to_redis(request, user, response):
    carts_str = request.COOKIES.get('carts')
    if carts_str is not None:
        carts_dict = pickle.loads(base64.b64decode(carts_str))
        redis_coon = get_redis_connection('carts')
        sku_id_count = redis_coon.hgetall('user_id:%s' % user.id)
        new_sku_id_count = {}
        for id, count in sku_id_count.items():
            new_sku_id_count[int(id)] = int(count)
        selected_list = []
        unselected_list = []
        new_carts_dict = {}
        sku_ids = carts_dict.keys()
        for sku_id in sku_ids:
            if sku_id in new_sku_id_count:
                new_carts_dict[sku_id] = carts_dict[sku_id]['count']
                # new_carts_dict[sku_id] = new_sku_id_count[sku_id] + carts_dict[sku_id]['count']

            else:
                new_carts_dict[sku_id] = carts_dict[sku_id]['count']
            if carts_dict[sku_id]['selected']:
                selected_list.append(sku_id)
            else:
                unselected_list.append(sku_id)
        redis_coon.hmset('user_id:%s' % user.id, new_carts_dict)
        if len(selected_list) > 0:
            redis_coon.sadd('user_selected:%s' % user.id, *selected_list)
        if len(unselected_list) > 0:
            redis_coon.srem('user_selected:%s' % user.id, *unselected_list)
        response.delete_cookie('carts')
        return response
    return response
